package com.sinog.auth.config;

import com.sinog.core.utilbean.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @desc 单点登录失败拦截器
 * @author liangkang
 * @date 2022-09-01
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Value("${gkzx.azbj.sso.type}")
    private Integer ossType;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,HttpServletResponse response,AuthenticationException exception) throws IOException, ServletException {
        String token = request.getParameter("token");
        Map<String,String[]> parameterMap = request.getParameterMap();
        boolean tokenFlag = parameterMap.containsKey("token");
        //是否带有token参数
            if(tokenFlag){
                if(StringUtils.isNotBlank(token)) {
                    if(Constants.Number.NUM_FOUR.equals(ossType)){
                        request.getSession().setAttribute("username_err","该系统未开启单点登录功能！请输入账号和密码登录");
                        response.sendRedirect("/auth/login");
                    }
                    if(Constants.Number.NUM_ONE.equals(ossType) || Constants.Number.NUM_TWO.equals(ossType)) {
                        request.getSession().setAttribute("token_parameter","手机号有误,");
                        response.sendRedirect("/auth/errorMsg");
                    } else if(Constants.Number.NUM_THREE.equals(ossType)) {
                        request.getSession().setAttribute("token_parameter","登录账号有误,");
                        response.sendRedirect("/auth/errorMsg");
                    } else {
                        request.getSession().setAttribute("username_err",exception.getMessage());
                        response.sendRedirect("/auth/login");
                    }
                }else if(tokenFlag) {
                    request.getSession().setAttribute("token_parameter","手机号为空,");
                    response.sendRedirect("/auth/errorMsg");
                }
            } else {
                request.getSession().setAttribute("username_err",exception.getMessage());
                response.sendRedirect("/auth/login");
            }

    }
}